package com.weido.nettyServer.core;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.multipart.Attribute;
import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder;
import io.netty.handler.codec.http.multipart.InterfaceHttpData;
import io.netty.util.CharsetUtil;
import io.netty.util.internal.StringUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static io.netty.handler.codec.http.HttpMethod.GET;
import static io.netty.handler.codec.http.HttpMethod.POST;

/**
 * Created by chenli on 2019/11/12.
 */
@Component
public class HttpRequest {
    ChannelHandlerContext ctx;
    FullHttpRequest req;

    public HttpRequest() {
    }

    public HttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) {
        this.ctx=ctx;
        this.req=req;
    }

    public String getUrl() {
        return req.uri();
    }
    public void setUrl(String url) {
         req.setUri(url);
    }

    public String getMethod() {
        return req.method().name();
    }

    public Map<String,Object> getParameterMap(){

        Map<String, Object> map = new HashMap<>();
        try {
            map= parse();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    public String getParamter(String param){
        if(StringUtil.isNullOrEmpty(param)){
            return null;
        }
        try {
            Map<String, Object> parse = parse();
            return (String) parse.get(param);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 解析请求参数
     * @return 包含所有请求参数的键值对, 如果没有参数, 则返回空Map
     *
     * @throws
     */
    private Map<String, Object> parse() throws Exception {
        HttpMethod  method= req.method();

        Map<String, Object> parmMap = new HashMap<String, Object>();
        if (method == GET) {
            // 是GET请求
            QueryStringDecoder decoder = new QueryStringDecoder(req.uri());
            decoder.parameters().entrySet().forEach( entry -> {
                // entry.getValue()是一个List, 只取第一个元素
                parmMap.put(entry.getKey(), entry.getValue().get(0));
            });
        } else if (method == POST) { // 是POST请求
            //HttpContent content = new DefaultHttpContent(Unpooled.wrappedBuffer(request.content()));
            HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(req);
            if(req.content().isReadable()){
                String json=req.content().toString(CharsetUtil.UTF_16);
//                parmMap.putAll(JsonUtils.getMapFromJSON(json));
            }
            decoder.offer(req);//form
            List<InterfaceHttpData> parmList = decoder.getBodyHttpDatas();
            for (InterfaceHttpData parm : parmList) {
                Attribute data = (Attribute) parm;
                parmMap.put(data.getName(), data.getValue());
            }
        } else {
            // 不支持其它方法
            throw new Exception("除[GET|POST]外，不支持其它方法!!!");
        }
        return parmMap;
    }
}


